package com.ruoyi.training.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.PracticeCheckInItemDTO;
import com.ruoyi.training.dto.PracticeClassStudentDTO;
import com.ruoyi.training.dto.StudentAppointmentDTO;
import com.ruoyi.training.dto.StudentPracticeCheckInDTO;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.service.*;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.AppointmentResultVO;
import com.ruoyi.training.vo.PracticeClassStudentVo;
import com.ruoyi.training.vo.TrainClassVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 实践预约班级学生中间Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-10-14
 */
@Service
public class PracticeClassStudentServiceImpl implements IPracticeClassStudentService {

    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    // 日期格式化（用于实践名称拼接，如“2025-09-09实践签到”）
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private PracticeClassStudentMapper practiceClassStudentMapper;

    @Autowired
    private IPracticeAppointmentService practiceAppointmentService;

    @Autowired
    private ITrainingClassService trainingClassService;

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private IClassStudentService classStudentService;

    @Autowired
    private IPracticeCheckInService practiceCheckInService;

    @Autowired
    private IProjectsService projectsService;

    @Autowired
    private PracticeClassMapper practiceClassMapper;

    @Autowired
    private PracticeAppointmentMapper practiceAppointmentMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Autowired
    private PracticeCheckInMapper practiceCheckInMapper;

    /**
     * 查询实践预约班级学生中间
     *
     * @param practiceClassStudentId 实践预约班级学生中间主键
     * @return 实践预约班级学生中间
     */
    @Override
    public PracticeClassStudent selectPracticeClassStudentByPracticeClassStudentId(String practiceClassStudentId) {
        return practiceClassStudentMapper.selectPracticeClassStudentByPracticeClassStudentId(practiceClassStudentId);
    }

    /**
     * 查询实践预约班级学生中间列表
     *
     * @param practiceClassStudent 实践预约班级学生中间
     * @return 实践预约班级学生中间
     */
    @Override
    public List<PracticeClassStudent> selectPracticeClassStudentList(PracticeClassStudent practiceClassStudent) {
        return practiceClassStudentMapper.selectPracticeClassStudentList(practiceClassStudent);
    }

    /**
     * 根据VO条件查询实践预约的学员信息
     *
     * @param practiceClassStudentVo 查询条件VO
     * @return 学员预约信息列表
     */
    @Override
    public List<PracticeClassStudentDTO> getPracticeClassStudents(PracticeClassStudentVo practiceClassStudentVo) {

        // 查询基础中间表数据
        List<PracticeClassStudent> practiceClassStudentList = practiceClassStudentMapper.selectByVo(practiceClassStudentVo);

        // 组装DTO数据
        List<PracticeClassStudentDTO> resultList = new ArrayList<>();
        for (PracticeClassStudent practiceClassStudent : practiceClassStudentList) {
            PracticeClassStudentDTO dto = new PracticeClassStudentDTO();

            // 设置中间表数据
            if (practiceClassStudent != null) {
                BeanUtils.copyProperties(practiceClassStudent, dto);
            }

            // 查询并设置实践预约信息
            PracticeAppointment appointment = practiceAppointmentService.selectPracticeAppointmentByPracticeAppointmentId(
                    practiceClassStudent.getPracticeAppointmentId());
            if (appointment != null) {
                dto.setPracticeAppointmentName(appointment.getPracticeAppointmentName());
                dto.setPracticeStartTime(appointment.getPracticeStartTime());
                dto.setPracticeEndTime(appointment.getPracticeEndTime());
                // 可扩展其他字段
            }

            //查询并设置项目信息
            Projects projects = projectsService.selectProjectsByProjectId(practiceClassStudent.getProjectId());
            //设置项目名称
            if (projects.getProjectName() != "" && projects.getProjectName() != null) {
                dto.setProjectName(projects.getProjectName());
            }

            // 查询并设置班级信息
            TrainClassVo trainClassVo = trainingClassService.selectTrainingClassVoByTrainingClassId(
                    practiceClassStudent.getTrainingClassId());
            if (trainClassVo != null) {
                //设置培训班编号
                if (trainClassVo.getTrainingClassCode() != null && !"".equals(trainClassVo.getTrainingClassCode())) {
                    dto.setTrainingClassCode(trainClassVo.getTrainingClassCode());
                }
                //设置培训班名称
                if (trainClassVo.getTrainingClassName() != null && !"".equals(trainClassVo.getTrainingClassName())) {
                    dto.setTrainingClassName(trainClassVo.getTrainingClassName());
                }
                //设置班主任1名称
                if (trainClassVo.getHeadTeacher1Name() != null && !"".equals(trainClassVo.getHeadTeacher1Name())) {
                    dto.setHeadTeacher1Name(trainClassVo.getHeadTeacher1Name());
                }
                //设置班主任2名称
                if (trainClassVo.getHeadTeacher2Name() != null && !"".equals(trainClassVo.getHeadTeacher2Name())) {
                    dto.setHeadTeacher2Name(trainClassVo.getHeadTeacher2Name());
                }
                // 可扩展其他字段
            }

            // 查询并设置学员信息
            Students student = studentsService.selectStudentsByStudentId(practiceClassStudent.getStudentId());
            if (student != null) {
                dto.setStudentName(student.getStudentName());
                dto.setPhonenumber(student.getPhonenumber());
                dto.setIdNumber(student.getIdNumber());
                if (student.getSex() != null && student.getSex() != "") {
                    if ("0".equals(student.getSex())) {
                        dto.setSex("男");
                    }
                    if ("1".equals(student.getSex())) {
                        dto.setSex("女");
                    }
                    if ("2".equals(student.getSex())) {
                        dto.setSex("未知");
                    }
                }

                // 可扩展其他字段
            }

            //预约来源
            if (practiceClassStudent.getAppointmentSource() != "" && practiceClassStudent.getAppointmentSource() != null) {
                if ("0".equals(practiceClassStudent.getAppointmentSource())) {
                    dto.setAppointmentSourceName("未预约");
                }
                if ("1".equals(practiceClassStudent.getAppointmentSource())) {
                    dto.setAppointmentSourceName("安排");
                }
            }
            //考试状态
            ClassStudent classStudent = new ClassStudent();
            classStudent.setStudentId(practiceClassStudent.getStudentId());
            classStudent.setStudentId(practiceClassStudent.getTrainingClassId());
            List<ClassStudent> classStudents = classStudentService.selectClassStudentList(classStudent);
            if (classStudents != null && !classStudents.isEmpty()) {
                // 获取第一个元素（List的索引从0开始）
                ClassStudent classStudent1 = classStudents.get(0);
                if (classStudent1.getExamStatus() != "" && classStudent1.getExamStatus() != null) {
                    if ("0".equals(classStudent1.getExamStatus())) {
                        dto.setExamStatusName("未排考");
                    }
                    if ("1".equals(classStudent1.getExamStatus())) {
                        dto.setExamStatusName("已排考");
                    }
                }
            }
            // 处理字典项
//            dto.setAppointmentSourceName(DictUtils.getDictLabel("appointment_source", dto.getAppointmentSource()));
//            dto.setAppointmentStatusName(DictUtils.getDictLabel("appointment_status", dto.getAppointmentStatus()));
//            dto.setExamStatusName(DictUtils.getDictLabel("exam_status", dto.getExamStatus()));

            resultList.add(dto);
        }

        return resultList;
    }


    /**
     * 新增实践预约班级学生中间
     *
     * @param practiceClassStudent 实践预约班级学生中间
     * @return 结果
     */
    @Override
    public int insertPracticeClassStudent(PracticeClassStudent practiceClassStudent) {
        practiceClassStudent.setCreateTime(DateUtils.getNowDate());
        return practiceClassStudentMapper.insertPracticeClassStudent(practiceClassStudent);
    }

    /**
     * 修改实践预约班级学生中间
     *
     * @param practiceClassStudent 实践预约班级学生中间
     * @return 结果
     */
    @Override
    public int updatePracticeClassStudent(PracticeClassStudent practiceClassStudent) {
        practiceClassStudent.setUpdateTime(DateUtils.getNowDate());
        return practiceClassStudentMapper.updatePracticeClassStudent(practiceClassStudent);
    }

    /**
     * 批量删除实践预约班级学生中间
     *
     * @param practiceClassStudentIds 需要删除的实践预约班级学生中间主键
     * @return 结果
     */
    @Override
    public int deletePracticeClassStudentByPracticeClassStudentIds(String[] practiceClassStudentIds) {
        return practiceClassStudentMapper.deletePracticeClassStudentByPracticeClassStudentIds(practiceClassStudentIds);
    }

    /**
     * 删除实践预约班级学生中间信息
     *
     * @param practiceClassStudentId 实践预约班级学生中间主键
     * @return 结果
     */
    @Override
    public int deletePracticeClassStudentByPracticeClassStudentId(String practiceClassStudentId) {
        return practiceClassStudentMapper.deletePracticeClassStudentByPracticeClassStudentId(practiceClassStudentId);
    }

    /**
     * 7.10.6添加预约-预约来源（安排）
     * lqx
     */
    @Override
    public int insertPracticeClassStudentList(List<PracticeClassStudent> practiceClassStudentList) {
        for (PracticeClassStudent practiceClassStudent : practiceClassStudentList) {
            //先判断是否存在但是是取消预约的状态
            List<PracticeClassStudent> practiceClassStudentList1 = practiceClassStudentMapper.selectPracticeClassStudentList(practiceClassStudent);
            if (practiceClassStudentList1 != null && !practiceClassStudentList1.isEmpty()) {
                //修改状态为已预约
                PracticeClassStudent practiceClassStudent1 = practiceClassStudentList1.get(0);
                practiceClassStudent1.setAppointmentStatus("0");
                practiceClassStudentMapper.updatePracticeClassStudent(practiceClassStudent1);
                //2.实践预约表班级表学生表中间表中新增一名学员后，同步一条未签到的数据到签到详情表中
                PracticeCheckIn practiceCheckIn = new PracticeCheckIn();
                //主键
                practiceCheckIn.setPracticeCheckId(String.valueOf(snowflake.nextId()));
                //实践预约表id
                practiceCheckIn.setPracticeAppointmentId(practiceClassStudent.getPracticeAppointmentId());
                //培训班id
                practiceCheckIn.setTrainingClassId(practiceClassStudent.getTrainingClassId());
                //学员id
                practiceCheckIn.setStudentId(practiceClassStudent.getStudentId());
                //培训项目id
                practiceCheckIn.setProjectId(practiceClassStudent.getProjectId());
                //签到状态，默认未签到-0
                practiceCheckIn.setCheckStatus("0");
                //新增签到
                practiceCheckInService.insertPracticeCheckIn(practiceCheckIn);
                continue;
            }

            //1新增添加预约信息
            //预约来源
            practiceClassStudent.setAppointmentSource("1");
            //默认实践状态为未实践
            practiceClassStudent.setPracticeStatus("0");
            //预约状态
            practiceClassStudent.setAppointmentStatus("0");
            //判断是否存在，若存在则跳过该次新增
            List<PracticeClassStudent> practiceClassStudentList2 = practiceClassStudentMapper.selectPracticeClassStudentList(practiceClassStudent);
            // 如果查询到有记录（列表非空），则跳过
            if (practiceClassStudentList2 != null && !practiceClassStudentList2.isEmpty()) {
                continue;
            }
            //预约时间
            practiceClassStudent.setAppointmentTime(DateUtils.getNowDate());
            //创建时间
            practiceClassStudent.setCreateTime(DateUtils.getNowDate());
            //创建人
            String username = SecurityUtils.getLoginUser().getSysUser().getNickName();
            practiceClassStudent.setCreateBy(username);
//            practiceClassStudent.setCreateBy("张三");
            //主键id
            practiceClassStudent.setPracticeClassStudentId(String.valueOf(snowflake.nextId()));
            //新增
            practiceClassStudentMapper.insertPracticeClassStudent(practiceClassStudent);

            //2.实践预约表班级表学生表中间表中新增一名学员后，同步一条未签到的数据到签到详情表中
            PracticeCheckIn practiceCheckIn = new PracticeCheckIn();
            //主键
            practiceCheckIn.setPracticeCheckId(String.valueOf(snowflake.nextId()));
            //实践预约表id
            practiceCheckIn.setPracticeAppointmentId(practiceClassStudent.getPracticeAppointmentId());
            //培训班id
            practiceCheckIn.setTrainingClassId(practiceClassStudent.getTrainingClassId());
            //学员id
            practiceCheckIn.setStudentId(practiceClassStudent.getStudentId());
            //培训项目id
            practiceCheckIn.setProjectId(practiceClassStudent.getProjectId());
            //签到状态，默认未签到-0
            practiceCheckIn.setCheckStatus("0");
            //新增签到
            practiceCheckInService.insertPracticeCheckIn(practiceCheckIn);
        }
        return 1;
    }

    /**
     * 取消预约，修改预约状态为2,同时删除对应的签到记录
     */
    @Override
    public int editAppointmentStatus(String[] practiceClassStudentIds) {
        //批量处理取消预约
        for (String practiceClassStudentId : practiceClassStudentIds) {
            //通过practiceClassStudentId修改预约状态
            PracticeClassStudent practiceClassStudent = new PracticeClassStudent();
            practiceClassStudent.setPracticeClassStudentId(practiceClassStudentId);
            practiceClassStudent.setAppointmentStatus("2");
            practiceClassStudentMapper.updatePracticeClassStudent(practiceClassStudent);

            //删除对应的签到记录
            PracticeClassStudent practiceClassStudent1 = practiceClassStudentMapper.selectPracticeClassStudentByPracticeClassStudentId(practiceClassStudentId);
            //new一个实践预约签到对象
            PracticeCheckIn practiceCheckIn = new PracticeCheckIn();
            //赋值实践预约id
            practiceCheckIn.setPracticeAppointmentId(practiceClassStudent1.getPracticeAppointmentId());
            //赋值学员id
            practiceCheckIn.setStudentId(practiceClassStudent1.getStudentId());
            //赋值班级id
            practiceCheckIn.setTrainingClassId(practiceClassStudent1.getTrainingClassId());
            //赋值培训项目id
            practiceCheckIn.setProjectId(practiceClassStudent1.getProjectId());
            //通过对象内容查询
            List<PracticeCheckIn> practiceCheckInList = practiceCheckInService.selectPracticeCheckInList(practiceCheckIn);
            //获取主键id
            PracticeCheckIn practiceCheckIn1 = practiceCheckInList.get(0);
            //删除对应的签到记录信息
            practiceCheckInService.deletePracticeCheckInByPracticeCheckId(practiceCheckIn1.getPracticeCheckId());
        }
        return 1;
    }

    /**
     * 新增接口：查询当前班级实践预约学员情况
     * lqx
     */
    @Override
    public AppointmentResultVO selectClassStudentAppointmentStatus(PracticeClassStudentDTO practiceClassStudentDTO) {
        // 1. 查询有效学员的预约信息（已过滤无效数据）
        List<StudentAppointmentDTO> validStudents = practiceClassStudentMapper.queryValidStudentAppointments(practiceClassStudentDTO);

        // 2. 分类已预约和未预约学员
        List<StudentAppointmentDTO> appointedList = new ArrayList<>();
        List<StudentAppointmentDTO> unappointedList = new ArrayList<>();

        for (StudentAppointmentDTO student : validStudents) {
            if ("0".equals(student.getAppointmentStatus())) {
                appointedList.add(student);
            } else {
                unappointedList.add(student);
            }
        }

        // 3. 封装返回结果
        AppointmentResultVO result = new AppointmentResultVO();
        result.setAppointedStudents(appointedList);
        result.setUnappointedStudents(unappointedList);
        return result;
    }

    /**
     * 查询班级学员的实践签到情况
     */
    @Override
    public List<StudentPracticeCheckInDTO> getStudentPracticeCheckIn(String classId) {
        // 1. 第一步：查询班级所有在班学员
        List<ClassStudent> classStudents = classStudentMapper.selectClassStudentsByClassId(classId);
        if (CollectionUtils.isEmpty(classStudents)) {
            return new ArrayList<>();
        }

        // 2. 第二步：查询班级关联的所有实践预约（含详情）
        List<PracticeAppointment> practiceAppointments = getClassPracticeAppointments(classId);
        if (CollectionUtils.isEmpty(practiceAppointments)) {
            // 无实践预约时，只返回学员基本信息，实践列为空
            return buildNoPracticeResult(classStudents);
        }

        // 3. 第三步：循环处理每个学员的实践签到情况
        List<StudentPracticeCheckInDTO> result = new ArrayList<>();
        for (ClassStudent classStudent : classStudents) {
            String studentId = classStudent.getStudentId();
            String registrationId = classStudent.getRegistrationId();

            // 3.1 封装学员基本信息
            Students student = studentsMapper.selectStudentsByStudentId(studentId);
            if (student == null || "2".equals(student.getDelFlag())) {
                continue; // 跳过已删除的学员
            }
            StudentPracticeCheckInDTO studentDTO = new StudentPracticeCheckInDTO();
            studentDTO.setStudentName(student.getStudentName());
            studentDTO.setIdNumber(student.getIdNumber());
            studentDTO.setPhoneNumber(student.getPhonenumber());

            String projectId = "";
            // 3.2 封装项目信息
            if (registrationId != null) {
                Registration registration = registrationMapper.selectByRegistrationId(registrationId);
                if (registration != null && registration.getProjectId() != null) {
                    projectId = registration.getProjectId();
                    Projects project = projectsMapper.selectProjectsByProjectId(registration.getProjectId());
                    if (project != null && "0".equals(project.getDelFlag())) {
                        studentDTO.setProjectName(project.getProjectName());
                    }
                }
            }

            // 3.3 处理每个实践的签到情况
            List<PracticeCheckInItemDTO> practiceItems = new ArrayList<>();
            int checkInCount = 0; // 签到次数
            int notCheckInCount = 0; // 未签到次数

            for (PracticeAppointment practice : practiceAppointments) {
                String practiceId = practice.getPracticeAppointmentId();
                PracticeCheckInItemDTO practiceItem = new PracticeCheckInItemDTO();
                    practiceItem.setPracticeAppointmentId(practiceId);
                // 拼接实践列标题（如“2025-09-09 设备操作实践”）
                String practiceName = sdf.format(practice.getPracticeStartTime()) + " " + practice.getPracticeAppointmentName();
                practiceItem.setPracticeName(practiceName);

                // 3.3.1 查学员对该实践的预约状态
                PracticeClassStudent appointment = practiceClassStudentMapper.selectByClassPracticeStudent(
                        classId, practiceId, studentId, projectId);

                if (appointment == null || "2".equals(appointment.getAppointmentStatus())) {
                    // 未预约或取消预约：签到状态设为“-”
                    practiceItem.setCheckStatusDesc("-");
                } else {
                    // 已预约：查签到记录
                    PracticeCheckIn checkIn = practiceCheckInMapper.selectByPracticeClassStudent(
                            practiceId, classId, studentId, projectId);

                    if (checkIn != null && "1".equals(checkIn.getCheckStatus())) {
                        // 已签到
                        practiceItem.setCheckStatusDesc("已签到");
                        checkInCount++;
                    } else {
                        // 未签到（无记录或状态为0）
                        practiceItem.setCheckStatusDesc("未签到");
                        notCheckInCount++;
                    }
                }
                practiceItems.add(practiceItem);
            }
            // 3.4 封装统计数据
            studentDTO.setPracticeCheckInItems(practiceItems);
            studentDTO.setCheckInCount(checkInCount);
            studentDTO.setNotCheckInCount(notCheckInCount);
            result.add(studentDTO);
        }
        return result;
    }

    /**
     * 辅助方法：根据班级ID查询所有有效的实践预约（含详情）
     */
    private List<PracticeAppointment> getClassPracticeAppointments(String classId) {
        List<PracticeClass> practiceClasses = practiceClassMapper.selectByClassId(classId);
        if (CollectionUtils.isEmpty(practiceClasses)) {
            return new ArrayList<>();
        }

        List<PracticeAppointment> practiceAppointments = new ArrayList<>();
        for (PracticeClass pc : practiceClasses) {
            String practiceId = pc.getPracticeAppointmentId();
            PracticeAppointment practice = practiceAppointmentMapper.selectById(practiceId);
            if (practice != null && "0".equals(practice.getDelTag())) {
                practiceAppointments.add(practice);
            }
        }
        return practiceAppointments;
    }

    /**
     * 辅助方法：无实践预约时，构建仅含学员信息的结果
     */
    private List<StudentPracticeCheckInDTO> buildNoPracticeResult(List<ClassStudent> classStudents) {
        List<StudentPracticeCheckInDTO> result = new ArrayList<>();
        for (ClassStudent classStudent : classStudents) {
            Students student = studentsMapper.selectStudentsByStudentId(classStudent.getStudentId());
            if (student == null || "2".equals(student.getDelFlag())) {
                continue;
            }

            StudentPracticeCheckInDTO studentDTO = new StudentPracticeCheckInDTO();
            studentDTO.setStudentName(student.getStudentName());
            studentDTO.setIdNumber(student.getIdNumber());
            studentDTO.setPhoneNumber(student.getPhonenumber());
            studentDTO.setPracticeCheckInItems(new ArrayList<>()); // 无实践
            studentDTO.setCheckInCount(0);
            studentDTO.setNotCheckInCount(0);

            // 补充项目信息
            if (classStudent.getRegistrationId() != null) {
                Registration registration = registrationMapper.selectByRegistrationId(classStudent.getRegistrationId());
                if (registration != null && registration.getProjectId() != null) {
                    Projects project = projectsMapper.selectProjectsByProjectId(registration.getProjectId());
                    if (project != null && "0".equals(project.getDelFlag())) {
                        studentDTO.setProjectName(project.getProjectName());
                    }
                }
            }
            result.add(studentDTO);
        }
        return result;
    }


}
